// @flow
import { createAction, createActions, handleActions, type ActionType } from 'redux-actions';
import produce from 'immer';
import { call, put, takeEvery, takeLatest, take, actionChannel } from 'redux-saga/effects';
import { createSagaActionType, createSagaAction, REQUEST, SUCCESS, FAILURE } from '../sagaUtils';
import * as AuthApi from 'lib/api/auth';
import storage, { keys } from 'lib/storage';
import { isPrivate } from 'ip';
/* ACTION TYPE */
const SET_WINDOW_NAME = createSagaActionType('base/SET_WINDOW_NAME');
const SHOW_USER_MENU = 'base/SHOW_USER_MENU';
const HIDE_USER_MENU = 'base/HIDE_USER_MENU';
const SET_LANDING_TYPE = 'base/SET_LANDING_TYPE';
const ENTER_LANDING = 'base/ENTER_LANDING';
const LANDING_DONE = 'base/LANDING_DONE';
const EXIT_LANDING = 'base/EXIT_LANDING';
/* ACTION PAYLOADS */
type windowNamePayload = {
    windowName: string,
    provider: string
};

export const actionCreators = {
    setWindowNameRequest: createAction(
        SET_WINDOW_NAME.REQUEST,
        (payload: windowNamePayload) => payload
    ),
    setWindowNameSuccess: createAction(
        SET_WINDOW_NAME.SUCCESS,
        (payload: windowNamePayload) => payload
    ),
    setWindowNameFailure: createAction(SET_WINDOW_NAME.FAILURE, (message: string) => message),
    showUserMenu: createAction(SHOW_USER_MENU),
    hideUserMenu: createAction(HIDE_USER_MENU),
    enterLanding: createAction(ENTER_LANDING),
    setLandingType: createAction(SET_LANDING_TYPE, (value: string) => value),
    setLandingDone: createAction(LANDING_DONE),
    exitLanding: createAction(EXIT_LANDING)
};
/* State Types */
type MenuItem = {
    key: number,
    name: string,
    to: string,
    isCollapse: boolean,
    isRoot: boolean,
    parentMenuKey?: number
};
type UserMenu = {
    isCollapse: boolean,
    subMenu: Array<MenuItem>
};
export type Base = {
    windowName: string,
    provider: string,
    landing: boolean,
    landingType?: 'bar' | 'full',
    headers: Array<MenuItem>,
    subMenu: UserMenu
};
/* INITIAL STATE */
const initialState: Base = {
    windowName: '',
    provider: '',
    landing: false,
    landingType: '',
    isDone: false,
    headers: [
        { key: 1, name: 'blog', to: '/blog', isCollapse: true, isRoot: true, parentMenuKey: 0 },
        { key: 2, name: 'things', to: '/things', isCollapse: true, isRoot: true, parentMenuKey: 0 },
        {
            key: 3,
            name: 'context',
            to: '/Context',
            isCollapse: true,
            isRoot: true,
            parentMenuKey: 0
        }
    ],
    userMenu: {
        isCollapse: true,
        subMenu: [
            { key: 0, name: '主页', to: '/', isCollapse: true, isRoot: true },
            { key: 1, name: '主页', to: '/', isCollapse: true, isRoot: true }
        ]
    }
};

export default handleActions(
    {
        [SET_WINDOW_NAME.SUCCESS]: (state, action: SetWindowNameAction) => {
            return produce(state, draft => {
                if (!action || !draft) return;
                draft.windowName = action.payload.windowName;
                draft.provider = action.payload.provider;
            });
        },
        [SHOW_USER_MENU]: state =>
            produce(state, draft => {
                draft.userMenu.isCollapse = false;
            }),
        [HIDE_USER_MENU]: state =>
            produce(state, draft => {
                draft.userMenu.isCollapse = true;
            }),
        [ENTER_LANDING]: state => {
            return produce(state, draft => {
                draft.landing = true;
                draft.isDone = false;
            });
        },
        [SET_LANDING_TYPE]: (state, action: setLandingTypeAction) => {
            return produce(state, draft => {
                if (!action || !draft) return;
                // bar,full
                draft.landingType = action.payload;
            });
        },
        [LANDING_DONE]: state => {
            return produce(state, draft => {
                draft.isDone = true;
            });
        },
        [EXIT_LANDING]: state => {
            return produce(state, draft => {
                draft.landing = false;
                draft.isDone = false;
            });
        }
    },
    initialState
);
function* setWindowNameSaga(action) {
    // const wn = yield actionChannel(SET_WINDOW_NAME.REQUEST);
    console.log(action.payload);
    // console.log(action.payload.provider);
    // console.log(action.payload.windowName);
    try {
        // const { payload } = take(actionChannel(wn));
        let name = storage.getStr(keys.name);
        const { windowName, provider } = action.payload;
        console.log('windowName:' + windowName + ',provider:' + provider);
        if (name === undefined) {
            name = null;
        }
        //如果window.name属性含有数据 优先使用
        if (window.name !== '') {
            name = window.name;
        }
        if (!windowName && windowName !== '') {
            name = windowName;
        }
        let sendWindowNameRet = null;

        if (provider !== null) {
            console.log('send windowname use 2');
            sendWindowNameRet = yield AuthApi.sendWindowName(name, provider);
        } else {
            console.log('send windowname use 1');
            sendWindowNameRet = yield AuthApi.sendWindowName(name);
        }

        // const windowName = yield call(AuthApi.sendWindowName, name ? name : null);
        // console.log(sendWindowNameRet.data.data);
        storage.setStr(keys.name, sendWindowNameRet.data.data.window_name);
        window.name = sendWindowNameRet.data.data.window_name;
        // console.log(SET_WINDOW_NAME.SUCCESS);
        yield put({
            type: SET_WINDOW_NAME.SUCCESS,
            payload: {
                windowName: sendWindowNameRet.data.data.window_name,
                provider: sendWindowNameRet.data.data.provider
            }
        });
    } catch (e) {
        yield put({ type: SET_WINDOW_NAME.FAILURE, message: e.message });
    }
}
export function* RootSaga() {
    console.log('base hello');
    yield takeEvery(SET_WINDOW_NAME.REQUEST, setWindowNameSaga);
}
